package top.birdhk.TestAPI.state;

import org.apache.commons.collections.IteratorUtils;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.checkpoint.ListCheckpointed;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import top.birdhk.TestAPI.beans.SensorReading;

import java.util.Collections;
import java.util.List;

public class StateTest_OperatorState {



    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

//        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 定义一个有状态的map操作
        SingleOutputStreamOperator<Integer> mapStream = inputStream.map(new MyCountMapper());


        mapStream.print("count:");

        env.execute();

    }


    public static class MyCountMapper implements MapFunction<SensorReading,Integer>, ListCheckpointed<Integer>{

        private Integer count = 0;

        @Override
        public Integer map(SensorReading sensorReading) throws Exception {
            return count++;
        }

        @Override
        public List<Integer> snapshotState(long l, long l1) throws Exception {
            return Collections.singletonList(count);
        }

        @Override
        public void restoreState(List<Integer> list) throws Exception {
//            for (Integer integer : list) {
//                count += integer;
//            }
        }
    }

}
